#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <fcntl.h>
#include <errno.h>

#define SOCKET_PATH "/tmp/uds_socket"
#define BUFFER_SIZE 4096  // 设置较大的接收缓冲区

void set_socket_nonblocking(int sock) {
    int flags = fcntl(sock, F_GETFL, 0);
    fcntl(sock, F_SETFL, flags | O_NONBLOCK);
}

void set_socket_recvbuf_size(int sock, int size) {
    if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF, &size, sizeof(size)) == -1) {
        perror("setsockopt SO_RCVBUF");
        exit(EXIT_FAILURE);
    }
}

int main() {
    int server_sock, client_sock;
    struct sockaddr_un addr;
    char buffer[BUFFER_SIZE];
    ssize_t num_bytes;

    // 创建 UNIX 域套接字
    server_sock = socket(AF_UNIX, SOCK_STREAM, 0);
    if (server_sock == -1) {
        perror("socket");
        exit(EXIT_FAILURE);
    }

    memset(&addr, 0, sizeof(struct sockaddr_un));
    addr.sun_family = AF_UNIX;
    strncpy(addr.sun_path, SOCKET_PATH, sizeof(addr.sun_path) - 1);

    // 绑定套接字
    if (bind(server_sock, (struct sockaddr *)&addr, sizeof(struct sockaddr_un)) == -1) {
        perror("bind");
        exit(EXIT_FAILURE);
    }

    // 设置接收缓冲区为较大的值，模拟服务器能够处理大量数据
    set_socket_recvbuf_size(server_sock, 4096); // 设置接收缓冲区为4096字节

    // 开始监听
    if (listen(server_sock, 5) == -1) {
        perror("listen");
        exit(EXIT_FAILURE);
    }

    printf("Server listening on %s\n", SOCKET_PATH);

    // 接受客户端连接
    client_sock = accept(server_sock, NULL, NULL);
    if (client_sock == -1) {
        perror("accept");
        exit(EXIT_FAILURE);
    }

    // 设置为非阻塞模式
    set_socket_nonblocking(client_sock);

    // 模拟处理大量数据
    while (1) {
        num_bytes = recv(client_sock, buffer, sizeof(buffer), 0);
        if (num_bytes == -1) {
            if (errno == EAGAIN || errno == EWOULDBLOCK) {
                //printf("No data received, buffer is full or not ready\n");
            } else {
                perror("recv");
                break;
            }
        } else if (num_bytes == 0) {
            printf("Client closed the connection\n");
            break;
        } else {
            buffer[num_bytes] = '\0';  // Null-terminate the received data
            //printf("Received: %s\n", buffer);
        }
    }

    close(client_sock);
    close(server_sock);
    unlink(SOCKET_PATH);

    return 0;
}
